package com.edu.hre.db.sql.pim;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.db.pojo.HreEmpBasicsalary;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.pim.EmpSalaryForm;
import com.edu.hre.struts.form.pim.EmpSalaryListForm;

public class EmpSalaryDAOService implements Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 3394301416150421253L;
	public static final String BEAN_NAME = "empSalaryDAOService";
	private BaseService baseService  = null;
	 
	public void setBaseService(BaseService baseService) {
		this.baseService = baseService;
	} 

	public ArrayList<EmpSalaryForm> getEmpSalaryList(int limit, int offset, int empNumber){

		ArrayList<EmpSalaryForm> listResult = new ArrayList<EmpSalaryForm>();

		String sql = "SELECT ebs.id AS col1," +
					" ebs.salary_component AS col2," +
					" per.payperiod_name AS col3," +
					" cur.currency_id AS col4, " +
					" cur.currency_name AS col5, " +
					" ebs.ebsal_basic_salary AS col6, " +
					" ebs.comments AS col7 " +

					" FROM hre_emp_basicsalary AS ebs," +
					" hre_pay_grade AS gra, " +
					" hre_pay_period_type AS per, " +
					" hre_currency_type AS cur " +
					
					" WHERE ebs.emp_number = ? " +
					" AND ebs.sal_grd_code = gra.id " +
					" AND ebs.payperiod_code = per.payperiod_code " +
					" AND gra.currency_id = cur.currency_id " +
					" ORDER BY ebs.date_created DESC";
		
		List <Object[]> listObject = baseService.listArrayObject(sql, limit, offset, empNumber);
		for(int i = 0; listObject != null && i < listObject.size(); i++){

			Object[] objs = listObject.get(i);
			EmpSalaryForm sal = new EmpSalaryForm();

			sal.setId(Integer.parseInt(CommonUtils.normalizeObjectToString(objs[1], "0")));
			sal.setEmpNumber(empNumber);
			sal.setName(CommonUtils.normalizeObjectToString(objs[2], ""));
			sal.setPayFrequency(CommonUtils.normalizeObjectToString(objs[3], ""));

			sal.setAmount(String.format("%,15.2f", Double.parseDouble(CommonUtils.normalizeObjectToString(objs[6], "0"))) + " VND");

			sal.setComment(CommonUtils.normalizeObjectToString(objs[7], ""));

			listResult.add(sal);
		}

		return listResult;
	}

	public int countEmpSalaries(int empNumber){

		int count = baseService.countByColumns(new String[]{"empNumber"}, new int[]{Compare.EQUAL}, new Integer[]{empNumber}, "id", HreEmpBasicsalary.class);
		return count < 0 ? 0 : count;
	}

	public void deleteSalaries(EmpSalaryListForm form){

		ArrayList<EmpSalaryForm> info = (ArrayList<EmpSalaryForm>) form.getAllSalaries();

		for (int i = 0; i < info.size(); i++) {
			
			try {

				EmpSalaryForm work = info.get(i);
				if (work.isSelected()) {
					baseService.deleteFirstPojo("id", Compare.EQUAL, work.getId(), null, null, 0, HreEmpBasicsalary.class);
				}
			} catch (Exception e) {
				CommonUtils.println(e.getMessage());
			}
		}
	}
}
